#include "EpollServerCplus.h"

using namespace std;

EpollEvents::EpollEvents()
{
	int CheckPos =0;
	int fds =0;
	int listenFd =0;
	g_epollFd =epoll_create(MAX_EVENTS);
}

EpollEvents::~EpollEvents()
{

}

void EpollEvents::EventSet(TServEvents* ev, int fd, void(EpollEvents:: *call_back)(int, int, void*), void *arg)
{
	ev->fd = fd;
	ev->call_back =  call_back;
	ev->events = 0;
	ev->arg = arg;
	ev->status = 0;
	ev->s_offset = 0;
	ev->last_active = time(NULL);
}

void EpollEvents::EventAdd(int epollFd, int events, TServEvents* ev)
{
	struct epoll_event epv = {0,{0}};
	int op;
	epv.data.ptr = ev;
	epv.events = ev->events = events;
	if(ev->status == 1)
	{
		op = EPOLL_CTL_MOD;
	}
	else
	{
		op = EPOLL_CTL_ADD;
		ev->status = 1;
	}
	if(epoll_ctl(epollFd,op,ev->fd,&epv) < 0)
	{
		printf("Event Add Failed[fd = %d], events[%d]\n", ev->fd, events);
	}
	else
		printf("Event Add Ok [fd=%d], op =%d , evnets[%0x]\n", ev->fd, op, events);
}

void EpollEvents::EventDel(int epollFd, TServEvents *ev)
{
	struct epoll_event epv = {0, {0}};
	if(ev->status != 1) return;
	epv.data.ptr = ev;
	ev->status = 0;
	epoll_ctl(epollFd, EPOLL_CTL_DEL, ev->fd, &epv);
}

void EpollEvents::AcceptConn(int fd, int events, void *arg)
{
	struct sockaddr_in sin;
	socklen_t len = sizeof(struct sockaddr_in);
	
	int nfd = -1, i;

	//accept
	printf("fd:%d\n",fd);
	if((nfd = accept(fd, (struct sockaddr*)&sin, &len)) == -1)
	{
		if(errno != EAGAIN && errno != EINTR)
		{	
		}
		printf("nfd:%d\n",nfd);
		//此处Accept所对应的listenfd描述符,一直处于打开状态,且活动状态,所以会一直调用AcceptConn函数?需要再看做确认!!!!
		printf("%s: accept, %d: %s\n",__func__,errno,strerror(errno));
		sleep(10);
		return;
	}

	do
	{
		for(i = 0; i < MAX_EVENTS; i++)
		{
			if(g_Events[i].status == 0)
			{
				break;
			}
		}
		if(i == MAX_EVENTS)
		{
			printf("%s:max connection limit[%d]",__func__,MAX_EVENTS);
		}
		
		// set nonblocking 将nfd设置为非阻塞的IO
		int iret = 0;
		if((iret = fcntl(nfd,F_SETFL, O_NONBLOCK)) < 0)
		{	
			printf("%s: fcntl nonblocking failed %d",__func__,iret);
			break;
		}
		// add a read event for receive data
		EventSet(&g_Events[i], nfd,NULL, &g_Events[i]);
		EventAdd(g_epollFd, EPOLLIN, &g_Events[i]);
	}
	while(0);
	printf("new conn[%s:%d]\n [time:%d]\n pos[%d]\n",inet_ntoa(sin.sin_addr),ntohs(sin.sin_port),g_Events[i].last_active,i);
}

void EpollEvents::InitListenSocket(short port)
{
	if((listenFd = socket(AF_INET, SOCK_STREAM, 0)) ==-1)
	{
		perror("creating sokect failed\n");
		exit(-1);
	}
	fcntl(listenFd, F_SETFL, O_NONBLOCK); // set non-blocking
	printf("server listen fd = %d\n",listenFd);
	EventSet(&g_Events[MAX_EVENTS],listenFd,&EpollEvents::AcceptConn,&g_Events[MAX_EVENTS]);
	// add listen socket
	EventAdd(g_epollFd, EPOLLIN , &g_Events[MAX_EVENTS]);
	//bind & listen
	sockaddr_in sin;
	bzero(&sin,sizeof(sin));
	
	sin.sin_family = AF_INET;
	sin.sin_addr.s_addr = INADDR_ANY;
	sin.sin_port = htons(port);
	if( bind(listenFd,(const sockaddr*) &sin, sizeof(sin)) != 0)
	{
		printf("bind failure\n");
		printf("errno: %d: strerror(errno):%s\n",errno,strerror(errno));
	}
	listen(listenFd, 10);
}

void EpollEvents::CheckTimeOut()
{
	long now = time(NULL);
	for(int i =0; i < 100; i++,CheckPos++)
	{
		if(CheckPos = MAX_EVENTS) CheckPos = 0; // doesn't check listen fd
		if(g_Events[CheckPos].status !=1) continue;
		long duration = now - g_Events[CheckPos].last_active;
		if(duration >= 10) // 60s timeout
		{
			close(g_Events[CheckPos].fd);
			printf("[fd= %d] timeout[%d--%d].\n",g_Events[CheckPos].fd,g_Events[CheckPos].last_active, now);
			EventDel(g_epollFd,&g_Events[CheckPos]);
		}
	}
}

int EpollEvents::EpollWait(struct epoll_event *events)
{
	fds = epoll_wait(g_epollFd,events, MAX_EVENTS, 0);	
	if(fds < 0)
	{
		printf("epoll_wait error, exit\n");
		return -1;
	}

	return fds;
}

int EpollEvents::GetListenID()
{
	return listenFd;
}



















